﻿/*
* 创建者：LIYINFAI
* 创建时间：2023/5/27 14:40:00
* 描述：
* --------------------------------------
* 修改说明：
* --------------------------------------
*/
using CommonLibrary.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 报警信息查询窗体
    /// </summary>
    public partial class FormAlarmQuery : HWFrmWithTitle
    {
        private List<AlarmInfo> mCurrentData = null;
        private int mCurrentPage = 0;
        private int mCountOfPage = 200;
        private int mMaxPage = 0;
        /// <summary>
        /// 构造函数
        /// </summary>
        public FormAlarmQuery()
        {
            InitializeComponent();
        }
        private void FormAlarmQuery_Load(object sender, EventArgs e)
        {
            InitControls();
            this.labelStart.Select();
        }
        private void InitControls()
        {
            var now = DateTime.Now;
            this.dateTimePickerEnd.Value = DateTime.Parse(now.ToString("yyyy-MM-dd HH:mm:59"));
            this.dateTimePickerStart.Value = DateTime.Parse(now.AddHours(-1).ToString("yyyy-MM-dd HH:mm:00"));
            this.textBoxContent.Text = string.Empty;
            DataGridViewInit();
        }
        private void ExecQueryData()
        {
            if (this.dataGridView.InvokeRequired)
            {
                this.dataGridView.Invoke(new Action(() => { ExecQueryData(); }));
            }
            else
            {
                CommonHelper.ShowWaiting(this, "正在查询数据，请稍候......");
                this.mCurrentData = null;
                this.mCurrentPage = 0;
                this.mMaxPage = 0;
                DateTime startTime = this.dateTimePickerStart.Value;
                DateTime endTime = this.dateTimePickerEnd.Value;
                string content = this.textBoxContent.Text.Trim();
                var result = AlarmsSQLiteDb.GetAlarms(startTime, endTime, content, false);
                FillData(result.alarms);
                CommonHelper.CloseWaiting();
            }
        }
        private void QueryData()
        {
            new Thread(() =>
            {
                ExecQueryData();
            })
            { IsBackground = true }.Start();
            Application.DoEvents();
        }
        private void buttonSearch_Click(object sender, EventArgs e)
        {
            QueryData();
            Application.DoEvents();
        }
        private void FillData(List<AlarmInfo> list)
        {
            this.mCurrentData = list;
            this.mCurrentPage = this.mCurrentPage == 0 ? 1 : this.mCurrentPage + 1;
            this.mMaxPage = list != null && list.Count > 0 ? (int)Math.Ceiling(list.Count * 1.0 / this.mCountOfPage) : 0;
            this.dataGridView.Rows.Clear();
            this.labelCurrent.Text = $"当前页码：{this.mCurrentPage}";
            this.labelTotal.Text = $"总页码：{this.mMaxPage}，总记录数：{(list == null ? 0 : list.Count)}";
            AddDataToGrid();
        }
        private void AddDataToGrid()
        {
            if (this.mCurrentPage <= this.mMaxPage && this.mCurrentData != null && this.mCurrentData.Count > 0)
            {
                this.dataGridView.Rows.Clear();
                var list = this.mCurrentData.Skip(this.mCountOfPage * (this.mCurrentPage - 1)).Take(this.mCountOfPage).ToList();
                foreach (var alarm in list)
                {
                    DataGridViewRow row = this.dataGridView.Rows[this.dataGridView.Rows.Add(1)];
                    row.Cells["code"].Value = alarm.AlarmCode;
                    row.Cells["name"].Value = alarm.AlarmContent;
                    row.Cells["start"].Value = alarm.StartTime;
                    row.Cells["end"].Value = alarm.EndTime;
                }
                this.labelCurrent.Text = $"当前页码：{this.mCurrentPage}";
            }
        }
        private void buttonPrev_Click(object sender, EventArgs e)
        {
            if (this.mCurrentPage - 1 >= 1)
            {
                this.mCurrentPage -= 1;
                AddDataToGrid();
            }
        }
        private void buttonNext_Click(object sender, EventArgs e)
        {
            if (this.mCurrentPage + 1 <= this.mMaxPage)
            {
                this.mCurrentPage += 1;
                AddDataToGrid();
            }
        }
        private void DataGridViewInit()
        {
            this.dataGridView.Columns.Clear();
            CommonHelper.CreateTextGridColumn(this.dataGridView, "code", "报警代码");
            CommonHelper.CreateTextGridColumn(this.dataGridView, "name", "报警内容");
            CommonHelper.CreateTextGridColumn(this.dataGridView, "start", "开始时间");
            CommonHelper.CreateTextGridColumn(this.dataGridView, "end", "结束时间");
            this.dataGridView.DoubleBufferedDataGirdView(true);
            this.dataGridView.InitStyle();
        }
        private void FormAlarmQuery_Shown(object sender, EventArgs e)
        {
        }
        private void FormAlarmQuery_FormClosing(object sender, FormClosingEventArgs e)
        {
        }
        private void buttonExport_Click(object sender, EventArgs e)
        {
            DirectlyOutputToExcel();
        }
        /// <summary>
        /// 通过条件查询数据并导出到Excel文档中
        /// </summary>
        private void DirectlyOutputToExcel()
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "*.xlsx|*.xlsx";
            DialogResult result = dialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                CommonHelper.ShowWaiting(this, "正在导出数据，请稍候......");
                DateTime startTime = this.dateTimePickerStart.Value;
                DateTime endTime = this.dateTimePickerEnd.Value;
                string content = this.textBoxContent.Text.Trim();
                try
                {
                    List<AlarmInfo> list = AlarmsSQLiteDb.GetAlarms(startTime, endTime, content, false).alarms;
                    bool outputResult = CommonHelper.WriteExcel(dialog.FileName, list, true, "报警记录",
                        (message) => { CommonHelper.ShowWaiting(this, message); }, true, true, new string[] { "Id" });
                    if (outputResult)
                    {
                        HWMessageBox.Show(this, "导出成功");
                        CommonHelper.OpenExcelFile(dialog.FileName);
                    }
                }
                catch (Exception ex)
                {
                    HWMessageBox.Show(this, ex.Message);
                    LogHelper.Error(ex);
                }
            }
            CommonHelper.CloseWaiting();
        }
    }
}
